package com.quickly.develop.common.commonExport;

import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;



@Service
public class CommonExportServiceImpl {

	private Logger logger = LoggerFactory.getLogger(CommonExportServiceImpl.class);

	public void commonExport(HttpServletRequest request, HttpServletResponse response, ExportBeanVo beanVo)  {

		try (/* workbook : 创建excel为文档 */
				XSSFWorkbook workbook = new XSSFWorkbook(); /**/
				OutputStream os = response.getOutputStream();/**/
		) {
			// XSSFSheet生成
			XSSFSheet sheetAt = workbook.createSheet(null == beanVo.getSheetName() ? "sheet_x" : beanVo.getSheetName());
			XSSFRow row;
			XSSFCell cell;

			XSSFCellStyle titleStyle = workbook.createCellStyle();
			// 03.设置水平对齐的样式为居中对齐;
			titleStyle.setAlignment(HorizontalAlignment.CENTER);
			// 04.设置垂直对齐的样式为居中对齐;
			titleStyle.setVerticalAlignment(VerticalAlignment.CENTER);
			/**/
			XSSFCellStyle cellStyle = workbook.createCellStyle();
			// 03.设置水平对齐的样式为居中对齐;
			cellStyle.setAlignment(HorizontalAlignment.CENTER);
			// 04.设置垂直对齐的样式为居中对齐;
			cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
			cellStyle.setBorderBottom(BorderStyle.THIN);
			cellStyle.setBorderLeft(BorderStyle.THIN);
			cellStyle.setBorderRight(BorderStyle.THIN);
			cellStyle.setBorderTop(BorderStyle.THIN);

			List<HashMap<String, String>> dataList = beanVo.getDataList();
			List<ExportColumnBean> columnList = beanVo.getColumnList();

			// 05.这个是合并单元格
			// 06.参数说明：1：开始行 2：结束行 3：开始列 4：结束列
			sheetAt.addMergedRegion(new CellRangeAddress(0, 0, 0, columnList.size() - 1));
			// row创建行
			int rowIndex = 0;
			if (null != columnList && columnList.size() > 0) {
				// ===第1行为标题===
				row = sheetAt.createRow(rowIndex);
				cell = row.createCell(0);
				cell.setCellValue(null == beanVo.getTitleName() ? "title_x" : beanVo.getTitleName());
				cell.setCellStyle(titleStyle);

				// ===第2行为表头===
				rowIndex += 1;
				// row:excel的表头
				// row创建行
				row = sheetAt.createRow(rowIndex);
				// cell：创建列
				for (int i = 0, length = columnList.size(); i < length; i++) {
					// Column列宽：
					sheetAt.setColumnWidth(i, 3000);
					// cell创建
					cell = row.createCell(i);
					cell.setCellValue(columnList.get(i).getValue());
					cell.setCellStyle(cellStyle);
				}
			}
			// ===第3行开始为数据===
			if (null != dataList && dataList.size() > 0) {
				// rowIndex:第n行数据
				for (Map<String, String> itemMap : dataList) {
					rowIndex += 1;
					// row创建行
					row = sheetAt.createRow(rowIndex);
					for (int i = 0, len = columnList.size(); i < len; i++) {
						// cell创建列
						cell = row.createCell(i);
						//
						cell.setCellValue(null == itemMap.get(columnList.get(i).getColumn()) ? " " : itemMap.get(columnList.get(i).getColumn()));
						cell.setCellStyle(cellStyle);
					}
				}
			}
			// 07.创建文件名
			String fileName = (null == beanVo.getFileName() ? "file_x" : beanVo.getFileName()) + ".xlsx";
			// 08.导出excel
			response.setContentType("application/vnd.ms-excel;charset=utf-8");
			response.setCharacterEncoding("UTF-8");
			response.setHeader("filename", URLEncoder.encode(fileName, "UTF-8"));
			response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
			response.setHeader("Access-Control-Expose-Headers", "filename");
			workbook.write(os);
		} catch (IOException | RuntimeException e) {
			// 10.失败的时候
			logger.error("exportList error ,errorMessage:{}", e.getMessage());
		}
	}

}
